package com.kye.express.business.waybill_list.subfragment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewAfterTextChangeEvent;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.waybill.waybill_detail.WayBillDetailActivity;
import com.kye.express.business.waybill_list.subfragment.viewbinder.WaybillListItemViewBinder;
import com.kye.express.databinding.FragmentWaybillListToSignBinding;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.logistics.LogisticsItemBean;
import com.kye.model.bean.logistics.LogisticsListResultBean;
import com.kye.model.bean.logistics.LogisticsUrgeResultBean;
import com.kye.model.bean.user.User;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import net.yslibrary.android.keyboardvisibilityevent.util.UIUtil;

import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 29/12/2017
 * @updated : 29/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 *
 */

public class WayBillListToSignFragment extends BaseAppCompatFragment implements WayBillListToSignContract.WayBillListToSignView, WaybillListItemViewBinder.OnItemListener {

    private static final int REQUEST_CODE_WAYBILL_DETAIL = 1000;
    protected FragmentWaybillListToSignBinding binding;
    protected WayBillListToSignContract.WayBillListToSignPresenter presenter;
    protected MultiTypeAdapter adapter;

    private MaterialDialog showUrgeSuccessDialog;
    private MaterialDialog showUrgeMessageDialog;
    private Disposable subscribeMessageInput;
    private String urgeMessage;
    private String selectedWaybill;

    public static WayBillListToSignFragment newInstance() {
        Bundle args = new Bundle();
        WayBillListToSignFragment fragment = new WayBillListToSignFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_waybill_list_to_sign, container, false);
        initViews(view, savedInstanceState);
        return view;
    }

    private void initViews(View view, Bundle savedInstanceState) {
        binding = DataBindingUtil.bind(view);
        adapter = new MultiTypeAdapter();
        adapter.register(LogisticsItemBean.class, new WaybillListItemViewBinder(this));
        binding.waybillList.setLayoutManager(new LinearLayoutManager(getActivity()));
        HorizontalDividerItemDecoration itemDecoration = new HorizontalDividerItemDecoration.Builder(getContext())
                .color(getResources().getColor(R.color.divider_two))
                .size((int) UIUtil.convertDpToPx(getContext(), 0.5f)).build();
        binding.waybillList.addItemDecoration(itemDecoration);
        binding.waybillList.setAdapter(adapter);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        presenter = new WayBillListToSignContract.WayBillListToSignPresenter();
        presenter.bind(this);
        presenter.onCreate(savedInstanceState);
        initEvents(savedInstanceState);
    }

    private void initEvents(Bundle savedInstanceState) {
        RxView.clicks(binding.llErrorServerCustom.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llErrorNetCustom.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(binding.llEmptyCustom.llEmpty)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        binding.statusLayout.showLoadingView();
                    }
                });
        binding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                presenter.loadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                presenter.refresh();
            }
        });
    }

    @Override
    protected void initDataFirstTime(boolean isForceUpdate, @Nullable Bundle savedInstanceState) {
        binding.statusLayout.showLoadingView();
        presenter.getUserInfo();
    }

    @Override
    public void onUser(User user) {
        if (user.isLogin()) {
            binding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
                @Override
                public void onLoading() {
                    presenter.refreshInit();
                }
            });
            presenter.refreshInit();
        } else {
            binding.statusLayout.showCustomView();
        }
    }

    @Override
    public void refreshInitSuccess(OpenApiResult<LogisticsListResultBean> result, LogisticsListResultBean logisticsListResultBean) {
//        {"code":30003,"msg":"查无数据","data":null,"success":true}
        if (result.getCode() == 30003 || logisticsListResultBean == null) {
            binding.statusLayout.showEmptyView();
            return;
        }
        List<LogisticsItemBean> data = logisticsListResultBean.getDatas();
        if (data == null || data.size() <= 0) {
            binding.statusLayout.showEmptyView();
        } else {
            binding.statusLayout.showContentView();
            adapter.setItems(data);
            adapter.notifyDataSetChanged();
            binding.refreshLayout.setEnableLoadmore(data.size() >= PageInfo.SIZE_DEFAULT);
        }
    }


    @Override
    public void refreshInitFailed(String msg) {
        ToastManager.showCenter(msg, Toast.LENGTH_SHORT);
        binding.statusLayout.showErrorServerView();
    }

    @Override
    public void refreshInitFailed(Throwable e) {
        ToastManager.showCenter(e.getMessage(), Toast.LENGTH_SHORT);
        binding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void refreshSuccess(LogisticsListResultBean orderListResultBean) {
        List<LogisticsItemBean> data = orderListResultBean.getDatas();
        binding.refreshLayout.finishRefresh(true);
        if (data == null || data.size() <= 0) {
            binding.statusLayout.showEmptyView();
        } else {
            adapter.setItems(data);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void refreshFailed(String msg) {
        ToastManager.showCenter(msg, Toast.LENGTH_SHORT);
        binding.refreshLayout.finishRefresh(false);
    }

    @Override
    public void refreshFailed(Throwable e) {
        ToastManager.showCenter(e.getMessage(), Toast.LENGTH_SHORT);
        binding.refreshLayout.finishRefresh(false);
    }

    @Override
    public void loadMoreSuccess(LogisticsListResultBean orderListResultBean) {
        List<LogisticsItemBean> data = orderListResultBean.getDatas();
        binding.refreshLayout.finishLoadmore(true);
        List<LogisticsItemBean> items = (List<LogisticsItemBean>) adapter.getItems();
        int startPosition = items.size();
        items.addAll(orderListResultBean.getDatas());
        adapter.notifyItemRangeInserted(startPosition, items.size());
        binding.refreshLayout.setEnableLoadmore(data.size() >= PageInfo.SIZE_DEFAULT);
    }

    @Override
    public void loadMoreFailed(String msg) {
        ToastManager.showCenter(msg, Toast.LENGTH_SHORT);
        binding.refreshLayout.finishLoadmore(false);
    }

    @Override
    public void loadMoreFailed(Throwable e) {
        ToastManager.showCenter(e.getMessage(), Toast.LENGTH_SHORT);
        binding.refreshLayout.finishLoadmore(false);
    }

    @Override
    public void onItemClicked(LogisticsItemBean itemBean) {
        Logger.d("onItemClicked : " + GsonUtils.toJsonString(itemBean, true));
//        WayBillDetailActivity.startActivity(getActivity(), REQUEST_CODE_WAYBILL_DETAIL, itemBean.getWaybill());
        Intent intent = WayBillDetailActivity.newStartIntent(getActivity(), itemBean.getWaybill());
        startActivityForResult(intent, REQUEST_CODE_WAYBILL_DETAIL);
    }

    @Override
    public void onItemUrgeClicked(LogisticsItemBean itemBean) {
        Logger.d("onItemClicked : " + GsonUtils.toJsonString(itemBean, true));
        /**
         * todo : 待签收可以催件
         */
        selectedWaybill = itemBean.getWaybill();
        presenter.postWaybillUrge(selectedWaybill, presenter.getUser());
    }

    @Override
    public void onItemScoreClicked(LogisticsItemBean itemBean) {
        Logger.d("onItemClicked : " + GsonUtils.toJsonString(itemBean, true));
        /**
         * todo : 待签收没有评分
         */
    }

    /**
     * 催件成功后显示对话框
     * @param logisticsUrgeResultBean
     */
    @Override
    public void postWayBillUrgeSuccess(LogisticsUrgeResultBean logisticsUrgeResultBean) {
        showUrgeSuccessDialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.order_logistics_urge, true)
                .positiveText("知道了")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        /**
                         * todo : 刷新
                         */
                        selectedWaybill = null;
                        binding.refreshLayout.autoRefresh();
                    }
                })
                .positiveColor(getResources().getColor(R.color.purple_0))
                .negativeText("留言")
                .negativeColor(getResources().getColor(R.color.black_666))
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        /**
                         * todo : 催件成功，更新view
                         */
                        showUrgeSuccessDialog.dismiss();
                        showWaybillUrgeMessagePostBox();

                    }
                })
                .backgroundColor(getResources().getColor(R.color.window_background))
                .show();
        showUrgeSuccessDialog.setCancelable(false);
    }

    /**
     * 显示留言dialog
     */
    public void showWaybillUrgeMessagePostBox() {
        showUrgeMessageDialog = new MaterialDialog.Builder(getActivity())
                .title("留言")
                .customView(R.layout.order_logistics_urge_message, true)
                .positiveText("确认")
                .positiveColor(getResources().getColor(R.color.purple_0))
                .negativeText("取消")
                .negativeColor(getResources().getColor(R.color.black_666))
                .backgroundColor(getResources().getColor(R.color.window_background))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (TextUtils.isEmpty(urgeMessage)) {
                            ToastManager.showCenterForShort("留言不能为空");
                        } else {
                            presenter.postWaybillUrgeMessage(urgeMessage, presenter.getUser(), selectedWaybill);
                        }
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        showUrgeMessageDialog.dismiss();
                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (subscribeMessageInput != null && !subscribeMessageInput.isDisposed()) {
                            subscribeMessageInput.dispose();
                            subscribeMessageInput = null;
                        }
                        /**
                         * todo : 刷新
                         */
                        selectedWaybill = null;
                        binding.refreshLayout.autoRefresh();
                    }
                })
                .show();
        showUrgeMessageDialog.setCancelable(false);
        subscribeMessageInput = RxTextView.afterTextChangeEvents(showUrgeMessageDialog.getCustomView().findViewById(R.id.message))
                .subscribe(new Consumer<TextViewAfterTextChangeEvent>() {
                    @Override
                    public void accept(TextViewAfterTextChangeEvent textViewAfterTextChangeEvent) throws Exception {
                        urgeMessage = textViewAfterTextChangeEvent.editable().toString();
                    }
                });
    }

    @Override
    public void postWayBillUrgeMessageSuccess() {
        if (showUrgeMessageDialog != null && showUrgeMessageDialog.isShowing()) {
            showUrgeMessageDialog.dismiss();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_WAYBILL_DETAIL && resultCode == Activity.RESULT_OK) {
            // 订单详情有催件操作,返回需要刷新
            binding.refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        presenter.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        presenter.unbind();
        super.onDestroy();
    }

    @Override
    public void onError() {

    }

    @Override
    public void onError(String msg) {

    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onLoaded() {

    }

}
